package GUI.anim;

import game.GameBase;
import game.Loadable;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;

import GUI.ImageStorage;

import util.INIGroup;

public class Animation implements Loadable {
	public class AnimationFrame
	{
		private Rectangle sourceRect;
		private Point offset;
		protected long delay;
		
		public AnimationFrame(int[] data)
		{
			if(data == null || data.length != 7) return;
			
			sourceRect = new Rectangle(data[0], data[1], data[2], data[3]);
			offset = new Point(data[4], data[5]);
			delay = data[6];
		}
	}
	
	private BufferedImage image = null;
	private String imageName = "";
	protected AnimationFrame[] frames = null;
	protected int frameCount = 0;
	private String tag = "";
	protected boolean swingMode = false;
	
	public Animation() { }
	
	public Animation(INIGroup g)
	{
		loadFromFile(g);
	}
	
	public void drawFrame(Graphics2D g, int i, int x, int y)
	{
		if(frames == null) return;
		if(i < 0 || i >= frameCount) return;
		
		AnimationFrame f = frames[i];
		//g.setColor(Color.red);
		//g.drawRect( x - f.offset.x, y - f.offset.y, f.sourceRect.width, f.sourceRect.height);
		
		g.drawImage(
				image, x - f.offset.x, y - f.offset.y, 
				x - f.offset.x + f.sourceRect.width, y - f.offset.y + f.sourceRect.height,
				f.sourceRect.x, f.sourceRect.y, 
				f.sourceRect.x + f.sourceRect.width, f.sourceRect.y + f.sourceRect.height,
				null);
	}

	@Override
	public boolean loadFromFile(INIGroup grupa) {
		tag = grupa.getString("Tag", "");
		frameCount = grupa.getInteger("FrameCount", 0);
		imageName = grupa.getString("ImageName", "");
		swingMode = grupa.getBoolean("SwingMode", false);
		System.out.println("ImageName : " + imageName);
		frames = new AnimationFrame[frameCount];
		for(int i = 0; i < frameCount; ++i)
		{
			int[] params = grupa.getIntList("Frame" + i);
			if(params != null)
				frames[i] = new AnimationFrame(params);
			else
				frames[i] = null;
		}
		return true;
	}

	@Override
	public String getTag() {
		return tag;
	}
	
	public int getFrameCount() {
		return frameCount;
	}

	@Override
	public void init() {
		image = ImageStorage.getImage(imageName);
	}
	
}
